package com.tenc.handle;

import com.tenc.utils.RedisUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Alan
 * @date 2021/7/9
 * @description 线程
 * @ClassName RunableImpl
 */
public class RunableImpl implements  Runnable{

    private static volatile AtomicLong room = new AtomicLong(9L);
    @Override
    public void run() {
        String massge = "";
        List<String> room1 = new LinkedList<>();
        try {
            while (true){
                boolean b = RedisUtil.lock("lock1");
//                boolean b = true;
                    if (b) {
                    room1  =(List<String>) RedisUtil.get("room1");
                    System.out.println(Thread.currentThread().getName()+":"+room1.size());
                    if(room1.size()<5){
                        long round = Math.round(Math.random() * 10);
                        if (round<6L){
                            quit(room1);
                        }else{
                            add(room1);
                        }
                    }else{
                        System.out.println(Thread.currentThread().getName()+"：房间已满");
                        break;
                    }
                    RedisUtil.deleteLock("lock1");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除锁；
            RedisUtil.deleteLock("lock1");
        }
    }


    public void add(List<String> room1){
        if (!room1.contains(Thread.currentThread().getName())){
            room1.add(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName()+":加入房间");
            RedisUtil.set("room1",room1);
        }
    }
    public void quit(List<String> room1){
        if (room1.contains(Thread.currentThread().getName())){
            room1.remove(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName()+":退出房间");
            RedisUtil.set("room1",room1);
        }
    }
}
